using System;
using System.Linq;
using Demo.Db;
using Demo.Models;
using Microsoft.EntityFrameworkCore;

namespace Demo.Repository
{
    public class EfRepository<T> : IRepository<T> where T : Father
    {
        private readonly DemoDb _db;
        private readonly DbSet<T> _table;

        public EfRepository()
        {
            _db = new DemoDb();
            _table = _db.Set<T>();
        }
        public IQueryable<T> table
        {
            get
            {
                return _table as IQueryable<T>;
            }
        }

        public void Delete(int id)
        {
            var entity = GetById(id);
            if (entity == null)
            {
                throw new System.Exception();
            }
            else
            {
                _table.Remove(entity);
                _db.SaveChanges();
            }
        }

        public T GetById(int id)
        {
            var entity = _table.Where(x => x.Id == id).FirstOrDefault();
            return entity;
        }

        public void Insert(T entity)
        {
            entity.IsActived = true;
            entity.IsDeleted = false;
            entity.CreatedTime = DateTime.Now;
            entity.DisplayOrder = 0;
            entity.Creator = 0;
            _table.Add(entity);
            _db.SaveChanges();
        }

        public void Update(T entity)
        {
            if (entity == null)
            {
                throw new System.Exception();
            }
            else
            {
                _table.Update(entity);
                _db.SaveChanges();
            }
        }
    }
}